package com.glory.brepda.activity.check;

import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.CheckQueryListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.entity.CheckSheetEntity;
import com.glory.brepda.entity.EqpInfoEntity;
import com.glory.brepda.entity.RepairFromListEntity;
import com.glory.brepda.entity.SheetInfoEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.datepicker.CustomDatePicker;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 点检履历
 */
public class SearchCheckActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etEqpWork)
    FreeUI_ClearEditText etEqpWork;
    @BindView(R.id.rbSingleEqp)
    RadioButton rbSingleEqp;
    @BindView(R.id.rbEqp)
    RadioButton rbEqp;
    @BindView(R.id.rbLocation)
    RadioButton rbLocation;
    @BindView(R.id.rbAll)
    RadioButton rbAll;
    @BindView(R.id.tvRepairID)
    TextView tvRepairID;
    @BindView(R.id.tvRepairType)
    TextView tvRepairType;
    @BindView(R.id.tvPositionAndJobNo)
    TextView tvPositionAndJobNo;
    @BindView(R.id.rvCheckInfoList)
    RecyclerView rvCheckInfoList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvBeginTime)
    TextView tvBeginTime;
    @BindView(R.id.ivBeginTimeArrow)
    ImageView ivBeginTimeArrow;
    @BindView(R.id.flBeginTimeList)
    FrameLayout flBeginTimeList;
    @BindView(R.id.tvEndTime)
    TextView tvEndTime;
    @BindView(R.id.ivEndTimeArrow)
    ImageView ivEndTimeArrow;
    @BindView(R.id.flEndTimeList)
    FrameLayout flEndTimeList;
    private CheckQueryListAdapter mAdapter;
    private String mEqpType;
    private String mLocation;
    private String mSelectorStr = "ALL";
    private String beginDate;
    private String endDate;
    private CustomDatePicker mDatePicker;
    boolean isBegin;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_search_check;
    }

    @Override
    protected void initView() {
        setMainLayout(llMain);
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        tvBaseSubmit.setText("查询");
        initRecyclerView(rvCheckInfoList,this);
        mAdapter = new CheckQueryListAdapter(null);
        mAdapter.isFirstOnly(true);
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        rvCheckInfoList.setAdapter(mAdapter);

        initDatePicker();
        beginDate = FreeApi_DateUtils.getAfterStringDate(new Date(System.currentTimeMillis()), "yyyy-MM-dd", -3);
        tvBeginTime.setText(beginDate);
        endDate = FreeApi_DateUtils.getAfterStringDate(new Date(System.currentTimeMillis()), "yyyy-MM-dd", 7);
        tvEndTime.setText(endDate);


        initEdit(etEqpWork, s -> LotUtils.searchEqpInfo(s, SearchCheckActivity.this, getSupportFragmentManager(), new LotUtils.netCallback<EqpInfoEntity>() {
            @Override
            public void onSuccess(EqpInfoEntity response) {
                if (response.getEQUIPMENT() != null) {
                    mEqpType = response.getEQUIPMENT().getEQPTYPE();
                    mLocation = response.getEQUIPMENT().getLOCATION();
                }
            }

            @Override
            public void onFail(Throwable t) {
                loadError(t,"EQPQUERY");
            }
        }));

        mAdapter.setOnCheckListener(item -> {
            if (item.getRESERVED3().equals("Open")){
                Bundle bundle = new Bundle();
                bundle.putString("EQPID",item.getEQUIPMENTID());
                bundle.putString("OBJECTRRN",item.getOBJECTRRN());
                if (item.getGROUP1().equals("巡检")){
                    if (actionControl("CheckInspectionActivity")){
                        return;
                    }
                    FreeApi_Utils.skipWithExtraIntent("header",bundle,this,CheckInspectionActivity.class);
                }else {
                    if (actionControl("NewCheckTableActivity")){
                        return;
                    }
                    FreeApi_Utils.skipWithExtraIntent("header",bundle,this,NewCheckTableActivity.class);
                }

            }else {
                FreeApi_ToastUtils.showFreeToast("当前状态不允许",this,false,0);
            }
        });
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvBaseSubmit, R.id.rbAll, R.id.rbSingleEqp, R.id.rbLocation, R.id.rbEqp,R.id.flBeginTimeList, R.id.flEndTimeList})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
//                if (actionControl("Submit28"))
//                    return;

                if (getText(etEqpWork).equals("")){
                    showToast("请扫描设备编号",false);
                    return;
                }

                requestData();
                break;
            case R.id.rbAll:
                mSelectorStr = "ALL";
                break;
            case R.id.rbSingleEqp:
                mSelectorStr = "SINGLE";
                break;
            case R.id.rbLocation:
                mSelectorStr = "LOCATION";
                break;
            case R.id.rbEqp:
                mSelectorStr = "EQPTYPE";
                break;
            case R.id.flBeginTimeList:
                isBegin = true;
                mDatePicker.show(System.currentTimeMillis());
                break;
            case R.id.flEndTimeList:
                isBegin = false;
                mDatePicker.show(System.currentTimeMillis());
                break;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        requestData();
    }

    private void requestData() {
        FreeUI_EntityCallBack<BaseResponseBean<CheckSheetEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<CheckSheetEntity>>
                (new TypeToken<BaseResponseBean<CheckSheetEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<CheckSheetEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    List<SheetInfoEntity> sheetlist = response.body().getResponse().getBody().getSHEETLIST();
                    if (sheetlist.size() <= 0){
                        showConfirmDialog("暂无数据");
                    }

                    mAdapter.setNewData(getData(sheetlist));
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<CheckSheetEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"CHECKSHEETQUERY");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EQUIPMENTID",getText(etEqpWork));
        map.addProperty("ACTIONTYPE","QUERYALL");
        map.addProperty("startTime", beginDate);
        map.addProperty("endTime", endDate);
        NetUtils.requestPostNet("IF.CHECKSHEETQUERY","Common",SearchCheckActivity.this,map,callBack);
    }

    private List<SheetInfoEntity> getData(List<SheetInfoEntity> sheetlist) {
        List<SheetInfoEntity> list = new ArrayList<>();
        switch (mSelectorStr){
            case "ALL":
                list = sheetlist;
                break;
            case "SINGLE":
                for (SheetInfoEntity entity : sheetlist){
                    if (entity.getEQUIPMENTID().equals(getText(etEqpWork))){
                        list.add(entity);
                    }
                }
                break;
            case "LOCATION":
                for (SheetInfoEntity entity : sheetlist){
                    if (entity.getRESERVED1().equals(mLocation)){
                        list.add(entity);
                    }
                }
                break;
            case "EQPTYPE":
                for (SheetInfoEntity entity : sheetlist){
                    if (entity.getEQUIPMENTTYPE().equals(mEqpType)){
                        list.add(entity);
                    }
                }
                break;
        }
        listSort(list);
        return list;
    }

    private void listSort(List<SheetInfoEntity> list) {
        Collections.sort(list, (sheetInfoEntity, t1) -> {
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            try {
                Date dt1 = format.parse(sheetInfoEntity.getCHECKDATE());
                Date dt2 = format.parse(t1.getCHECKDATE());
                if (dt1.getTime() < dt2.getTime()) {
                    return 1;
                } else if (dt1.getTime() > dt2.getTime()) {
                    return -1;
                } else {
                    return 0;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 0;
        });
    }

    private void initDatePicker() {
        long beginTimestamp = FreeApi_DateUtils.str2Long("1992-03-20", false);
        long endTimestamp = FreeApi_DateUtils.str2Long("2222-02-22", false);

        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = new CustomDatePicker(this, timestamp -> {
            if (isBegin) {
                beginDate = FreeApi_DateUtils.long2Str(timestamp, false);
                tvBeginTime.setText(beginDate);
            } else {
                endDate = FreeApi_DateUtils.long2Str(timestamp, false);
                tvEndTime.setText(endDate);
            }

        }, beginTimestamp, endTimestamp);
        // 不允许点击屏幕或物理返回键关闭
        mDatePicker.setCancelable(true);
        // 不显示时和分
        mDatePicker.setCanShowPreciseTime(false);
        // 不允许循环滚动
        mDatePicker.setScrollLoop(false);
        // 不允许滚动动画
        mDatePicker.setCanShowAnim(false);
    }

}
